$(function () {
  //调用获取用户信息
  getUserInfo();
  $("#btnLogOut").on("click", function () {
    console.log(1);
    layer.confirm("确认是否退出", { icon: 3, title: "提示" }, function (index) {
      //do something
      localStorage.removeItem("token");
      location.href = "/login.html";
      layer.close(index);
    });
  });
});
//获取用户信息函数
function getUserInfo() {
  $.ajax({
    url: "/my/userinfo",
    method: "GET",
    /* headers: {
      Authorization: localStorage.getItem("token") || "",
    },*/
    success(res) {
      if (res.status !== 0) return layer.msg(res.message);
      //渲染用户头像
      renderAvatar(res.data);
    },
    complete(res) {
      if (
        res.responseJSON.status === 1 &&
        res.responseJSON.message === "身份认证失败！"
      ) {
        localStorage.removeItem("token");
        location.href = "/login.html";
      }
    },
  });
}
function renderAvatar(user) {
  const username = user.nickname || user.username;
  $("#welcome").html(`欢迎 ${username}`);
  if (user.user_pic) {
    $(".layui-nav-img").attr("src", user.user_pic).show();
    $(".text-avatar").hide();
  } else {
    $(".layui-nav-img").hide();
    const firstName = username[0].toUpperCase();
    $(".text-avatar").html(firstName).show();
  }
}
